home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / editor / snmp_0_1.zip / snmp-0.1 / aka / snmp / Snmp.java < prev    next >
Text File  |  1997-06-09  |  11KB  |  362 lines

  1. /*
  2. Snmp Library
  3. Copyright (C) 1997 Alex Kowalenko Associates Pty Ltd. All rights reserved.
  4.  
  5. This software maybe be free distributed, any any form, without fee, 
  6. but may not be modified in any way without express permission of 
  7. the directors of Alex Kowalenko Associates Pty Ltd. 
  8.  
  9. Alex Kowalenko Associates Pty Ltd makes no representations or
  10. warranties about the suitabililty of the software, not even the
  11. implied warranty of merchantability or fitness for any particular
  12. purpose.    
  13. */
  14.  
  15. package aka.snmp;
  16.  
  17. import java.util.*;
  18. import java.io.*;
  19. import java.net.*;
  20.  
  21. /**
  22.  * This class implements a SNMP client.  The operations supported 
  23.  * are SNMP Get, GetNext, and Set.  Also a Walk operation is implemented
  24.  * 
  25.  * @version     $Id: Snmp.java,v 1.10 1997/05/29 12:54:32 alex Exp $
  26.  * @author      Alex Kowalenko
  27.  */
  28.  
  29. public class Snmp {  
  30.  
  31.   private MibManager _mibs;
  32.   private ConnectManager _conMan;
  33.   private int _requestID;
  34.   private String _communityName;
  35.   
  36. /**
  37.  * Creation of client
  38.  * @parameter cacheSize - sets the size of the cache of 
  39.  * connections to multiple machines.
  40.  */
  41.  
  42.   public Snmp(short cacheSize) {
  43.       _mibs = new MibManagerSerializer();
  44.       _conMan = new ConnectManager(cacheSize);
  45.       _requestID = 0;
  46.   };
  47.  
  48. /**
  49.  * Creation of client, default size of cache of 5.
  50.  */ 
  51.  
  52.   public Snmp() {
  53.       this((short)5);
  54.   };
  55.  
  56.   
  57. /**
  58.  * Read the SNMP objects from this file into memory.  The file
  59.  * is a serializer version of the Managed Object Definitions.
  60.  */
  61.  
  62.   public void readFile(String file) 
  63.       throws IOException, SnmpMibException, FileNotFoundException {
  64.       ((MibManagerSerializer)_mibs).SerializeFromFile(file);
  65.       return;
  66.   };
  67.  
  68. /**
  69.  * Read the SNMP objects from this file into memory.  The file
  70.  * is a MIB file that contains all the  managed objects.
  71.  */
  72.  
  73.   public void readMibFile(String file) 
  74.       throws SnmpMibException, FileNotFoundException {
  75.       ((MibManagerParser)_mibs).addFromMibDefFile(file);
  76.       return;
  77.   };
  78.     
  79. /**
  80.  * Set the community name that is going to be used.
  81.  */
  82.  
  83.   public void setCommunityName(String name) {
  84.       _communityName = name;
  85.   };
  86.  
  87. /**
  88.  * Set timeout for SNMP response to seconds.
  89.  */
  90.  
  91.   public void setTimeOut(int seconds) {
  92.       _conMan.setTimeOut(seconds);
  93.   };
  94.  
  95. /** 
  96.  * Dump out MIB for debugging
  97.  */
  98.  
  99.   public void dumpMib() {
  100.       _mibs.dump();
  101.       return;
  102.   };
  103.   
  104. /**
  105.  * SNMP Get Operation.  Get the value of the variable and instance
  106.  * from the SNMP agent at address.  It's value is returned as a Type.
  107.  * Exceptions are thrown if the operation is unsuccessful.
  108.  */
  109.   
  110.   public Type get(String address, String variable, int instance)
  111.       throws SnmpException, UnknownHostException, 
  112.       IOException, SocketException {
  113.           PDU pdu = new PDU(address, 
  114.                 Operation.GET, 
  115.                 _communityName,  
  116.                 _requestID++);
  117.           ObjectId oid = _mibs.containsName(variable);
  118.           if(oid.equals(ObjectId.Void)) 
  119.           throw new SnmpException("Can't find variable name " + 
  120.                       variable);
  121.           oid.addInstance(instance);
  122.           pdu.addVar(oid);
  123.           PDU resultPdu;
  124.  
  125.           resultPdu = _conMan.send(address, pdu);
  126.           if(resultPdu.errorStatus().value() == SnmpError.NO_ERROR) {
  127.           return resultPdu.var(0).value();
  128.           }
  129.           else {
  130.           throw new SnmpException("Snmp error occured : " + 
  131.                       resultPdu.errorStatus() 
  132.                       + " in index : " + 
  133.                       resultPdu.errorIndex());
  134.           }
  135.   };
  136.   
  137. /**
  138.  * SNMP GetNext Operation.  Get the value of the variable and instance from 
  139.  * the SNMP agent at address.  It's value is returned in result, the next
  140.  * variable in the agents MIB hierachy is returned in nextVariable.
  141.  * A exception is generated if the operation is unsuccessful.
  142.  */
  143.  
  144.   public Type getNext(String address, 
  145.               String variable, 
  146.               int instance, 
  147.               StringBuffer newVariable)
  148.       throws SnmpException, UnknownHostException, 
  149.       IOException, SocketException  {
  150.           PDU pdu = new PDU(address, 
  151.                 Operation.GET_NEXT, 
  152.                 _communityName, 
  153.                 _requestID++);
  154.           ObjectId oid = _mibs.baseForm(variable);
  155.           if(oid.equals(ObjectId.Void))
  156.           throw new SnmpException("Can't find variable name '" + 
  157.                       variable + "'");
  158.           if(instance >= 0)
  159.           oid.addInstance(instance);
  160.           pdu.addVar(oid);
  161.           PDU resultPdu;
  162.           resultPdu = _conMan.send(address, pdu);
  163.   
  164.           if(resultPdu.errorStatus().value() == SnmpError.NO_ERROR) {
  165.           String result = resultPdu.var(0).value().toString();
  166.           ObjectId id = resultPdu.var(0).oid();
  167.           String nextVariable = _mibs.reduceToName(id);
  168.           if(nextVariable.length() == 0)
  169.               nextVariable = id.toString();
  170.           newVariable.append(nextVariable);
  171.           return resultPdu.var(0).value();
  172.           }
  173.           else
  174.           throw new SnmpException("Snmp error occured : " + 
  175.                       resultPdu.errorStatus() +  
  176.                       "in index : " +
  177.                       resultPdu.errorIndex());
  178.   };
  179.   
  180. /**
  181.  * SNMP GetNext Operation.  Get the value of the variable from the SNMP 
  182.  * agent at address.  It's value is returned in result, the next
  183.  * variable in the agents MIB hierachy is returned in nextVariable.
  184.  * A exception is generated if a problem occurs.  This same SNMP operation 
  185.  * as the one above, but it differs that only an ID is given which could 
  186.  * or could not have an instance attached to it
  187.  */
  188.  
  189.   public Type getNext(String address, String variable, StringBuffer result) 
  190.       throws SnmpException, UnknownHostException, 
  191.       IOException, SocketException  {    
  192.           return getNext(address, variable, -1, result);
  193.   };
  194.  
  195. /**
  196.  * Performs a multiple SNMP GetNext starting at variable
  197.  * in the MIB hierachy to the SNMP agent at address.
  198.  * Results are returned in the Vector result, which has elements of arrays
  199.  * of two elements, the first element in the array is a String which
  200.  * has the object name, the second element is a Type object with the
  201.  * value of the variable.
  202.  */
  203.  
  204.   public void walk(String address, String variable, Vector result)
  205.       throws SnmpException, UnknownHostException, 
  206.       IOException, SocketException  {
  207.           ObjectId lastID; 
  208.           ObjectId thisID = _mibs.containsName(variable);
  209.           ObjectId topID = thisID; 
  210.           if(thisID.equals(ObjectId.Void))
  211.           throw new SnmpException("Can't find variable name '" + 
  212.                       variable + "'");
  213.           do {
  214.           PDU pdu = new PDU(address, 
  215.                     Operation.GET_NEXT, 
  216.                     _communityName, 
  217.                     _requestID++);
  218.           pdu.addVar(thisID);
  219.           PDU resultPdu;
  220.           resultPdu = _conMan.send(address, pdu);
  221.     
  222.           if(resultPdu.errorStatus().value() == SnmpError.NO_ERROR) {
  223.               Object nextVariable[] = new Object[2];
  224.               ObjectId id = resultPdu.var(0).oid();
  225.               lastID = thisID;
  226.               thisID = id;
  227.               nextVariable[0] = _mibs.reduceToName(id);
  228.               if(((String)nextVariable[0]).length() == 0)
  229.               nextVariable[0] = id.toString();
  230.               nextVariable[1] = resultPdu.var(0).value();
  231.               result.addElement(nextVariable);
  232.               continue;
  233.           }
  234.           else
  235.               throw new SnmpException("Snmp error occured : " + 
  236.                           resultPdu.errorStatus() + 
  237.                           " in index : " + 
  238.                           resultPdu.errorIndex());  
  239.           } while(thisID.isUnder(topID) && !(lastID.equals(thisID)));
  240.           result.removeElementAt(result.size() - 1);
  241.           return;
  242.   };
  243.   
  244. /**
  245.  * Performs the SNMP Set operation. Set the value of the 
  246.  * variable of instance to value at SNMP agent at address
  247.  * A exception is generated when the operation was unsuccessful.
  248.  */
  249.  
  250.   public boolean setValue(String address, 
  251.               String variable, 
  252.               int instance, 
  253.               String value) 
  254.       throws SnmpException, UnknownHostException, 
  255.                   IOException, SocketException  {    
  256.           PDU pdu = new PDU(address, 
  257.                 Operation.SET, 
  258.                 _communityName, 
  259.                 _requestID++);
  260.       ObjectId oid = _mibs.containsName(variable);
  261.       if(oid.equals(ObjectId.Void)) 
  262.           throw new SnmpException("Can't find variable name");
  263.       
  264.       oid.addInstance(instance);
  265.       // Convert string into type
  266.       Type t = Type.make((_mibs.contains(oid)).type().typeName());
  267.       t.read(value);
  268.       pdu.addVar(oid,t);
  269.       PDU resultPdu;
  270.       resultPdu = _conMan.send(address, pdu);
  271.       if(resultPdu.errorStatus().value() == SnmpError.NO_ERROR) {
  272.           return true;
  273.       }
  274.       else
  275.           throw new SnmpException("Snmp error occured : " + 
  276.                       resultPdu.errorStatus() +
  277.                       ", Snmp index : " + 
  278.                       resultPdu.errorIndex());
  279.   }
  280.  
  281. /**
  282.  * Test Harness
  283.  */
  284.   
  285.   public static void main(String args[]) {
  286.  
  287.       if(args.length < 3) {
  288.       System.out.println("Snmp command host communityName oid [ value ] ");
  289.       return;
  290.       };
  291.  
  292.       Snmp snmp = new Snmp();
  293.       try {
  294.       snmp.readFile("mibs.ser");
  295.       } catch (Exception e) {
  296.       System.err.println("Problem reading mib file " + e.getMessage());
  297.       return;
  298.       }
  299.       snmp.setTimeOut(3);
  300.  
  301.       snmp.setCommunityName(args[2]);
  302.   
  303.       try {
  304.       if(args[0].equals("get")) {
  305.           Type resultVal = snmp.get(args[1], args[3], 0);
  306.           System.out.println(args[3] + " = " + resultVal);
  307.           return;
  308.       }
  309.       else if(args[0].equals("getnext")) {
  310.           StringBuffer nextVar = new StringBuffer();
  311.           Type resultVal = snmp.getNext(args[1], args[3], 0, nextVar);
  312.           System.out.println(nextVar + " = " + resultVal);
  313.           return;
  314.       }
  315.       else if(args[0].equals("set")) {
  316.           boolean resultBoolean = snmp.setValue(args[1], args[3], 0, args[4]);
  317.           System.out.println(args[3] + " = " + resultBoolean);
  318.           return;
  319.       }
  320.       else if(args[0].equals("walk")) {
  321.           Vector resultVector = new Vector();
  322.           long current = 0;
  323.           try {
  324.           snmp.walk(args[1], args[3], resultVector);
  325.           } catch(Exception e) {
  326.           System.err.println("Problem with " + args[0] + ": " + e.getMessage());
  327.           e.printStackTrace();
  328.           }
  329.            for(Enumeration e = resultVector.elements(); 
  330.            e.hasMoreElements(); ) {
  331.            Object element[] = (Object[]) e.nextElement();
  332.            System.out.println((String) element[0] + " = " + 
  333.                       (Type) element[1]);
  334.            }      
  335.           return;
  336.       } 
  337.       else if(args[0].equals("test")) {
  338.           Vector resultVector = new Vector();
  339.           long current = 0;
  340.           try {
  341.           System.gc(); 
  342.           current = System.currentTimeMillis();
  343.           snmp.walk(args[1], args[3], resultVector);
  344.           current = System.currentTimeMillis() - current;
  345.           } catch(Exception e) {
  346.           System.err.println("Problem with " + args[0] + ": " + e.getMessage());
  347.           e.printStackTrace();
  348.           }
  349.           System.out.println("Time : " + current + "ms");
  350.           return;
  351.       }
  352.       else {
  353.           System.out.println("Unknown command : " + args[0]);
  354.           return;
  355.       };
  356.       } catch(Exception e) {
  357.       System.err.println("Problem with " + args[0] + ": " + e.getMessage());
  358.       }
  359.   };
  360.  
  361. }
  362.